<script setup lang="ts">
import {Close, Refresh} from "@element-plus/icons-vue";
import {tagViewStorage} from "@/storage";
import {useRoute, useRouter} from "vue-router";
import {computed, nextTick} from "vue";
import {emitter} from '@/utils/mitt'

const route = useRoute()
const router = useRouter()

const onRemove = (view: WebRouteRaw) => {
  const index = tagViewStorage.value.findIndex(f => f.id === view.id)
  nextTick(() => {
    tagViewStorage.value.splice(index, 1)
    const name = view.query.type || ''
    if (name === 'web') {
      router.push({name})
    } else if (name === 'server') {
      router.push({name})
    } else {
      const view = tagViewStorage.value[index] || tagViewStorage.value[index - 1]
      if (view) openPage(view)
    }
  })
}

const onRefresh = () => {
  emitter.emit('onTagsViewRefreshRouterView')
}

const openPage = (view: WebRouteRaw) => {
  router.push({
    path: view.path,
    query: view.query
  })
}

const list = computed(() => {
  return tagViewStorage.value.filter(f => Object.keys(f.query).length)
})

</script>

<template>
  <el-scrollbar class="tag-view" v-if="list.length">
    <div class="tag">
      <div v-for="(view, index) in list" :key="index" class="tag-item cursor-pointer"
           :class="{ 'active': view.id === route.fullPath }" @click="openPage(view)">
        <span>{{ view.title }}</span>
        <el-icon v-if="view.id === route.fullPath" @click.stop="onRefresh()" class="icon">
          <Refresh/>
        </el-icon>
        <el-icon v-if="view.id !== '/home'" @click.stop="onRemove(view)" class="icon">
          <Close/>
        </el-icon>
      </div>
    </div>
  </el-scrollbar>
</template>
<style scoped>
.tag-view {
  height: 25px;
  border-bottom: 1px solid var(--el-border-color);
  font-size: 12px;
  flex-shrink: 0;
}

.tag {
  display: flex;
  align-items: center;
  height: 24px;
}

.tag-item {
  min-width: 50px;
  height: 85%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: all ease-in-out 0.2s;
  outline: 1px solid var(--el-border-color);
  margin-left: 5px;
  position: relative;
  padding-left: 7px;
  padding-right: 3px;
}

.tag-item .icon {
  padding: 3px;
  font-size: 18px;
}

.tag-item.active {
  color: var(--el-color-white);
  background-color: var(--el-color-primary);
}
</style>
